<?php
/**
 * @Author: Ron Chen
 * @Date:   2017-03-25 00:31:10
 * @Last Modified by:   Ron Chen
 * @Last Modified time: 2018-04-23 22:44:28
 */
namespace app\controllers;

use Yii;
use yii\web\Response;
use yii\helpers\Url;
use app\models\InsurancePolicy;
use app\models\InsurancePrice;
use app\models\InsurancePolicyInsured;
use app\services\PolicyServices;
use app\models\InsurancePolicyHolder;
/**
* @name 购买信息填写
*/
class BuyController extends BaseController{

	public $enableCsrfValidation = false;

	public function init(){
		parent::init();
		$this->layout = "insurance-buy";
	}

	/**
	 * @name 确认购买
	 */
	public function actionConfirm(){
		$policy_id = trim($this->request->get('id',''));
		$policy_info = InsurancePolicy::findOne($policy_id);

		$message   = "";
		if ($this->request->isPost) {
			$policy_info->premium_total = $this->request->post('premium_total');
			$policy_info->number = $this->request->post('number');
			$policy_info->is_bill = trim($this->request->post('is_bill')) == "on" ? 1 : 0;
			$policy_info->issue_date  = $this->request->post('effect_date');
			$policy_info->effect_date = $this->request->post('effect_date');
			$policy_info->expire_date = date("Y-m-d",strtotime("+{$policy_info->price_day} days",strtotime($policy_info->effect_date)));
			
			// 生成保单，提示保单错误信息
			$policyRef = $policy_info->policy_id;
			if ($policy_info->save() && empty($policy_info->policy_id)) {
				$policy_service = new PolicyServices();
				$data = $policy_service->addPolicyOrder($policy_id);
				
				$xml_data = simplexml_load_string($data);
				if (!$xml_data) {
					$message = $data;
				}
				$policyRef = "";
				if ($xml_data->Head->ResponseCode && $xml_data->Head->ErrorCode == '0000') {
					// 更新保单号
					$policyRef = $xml_data->Body->PolicyRef;
					$policy_info->policy_id = $policyRef;
					$policy_info->desc = json_encode([
							"PolicyRef" => $policyRef,
							"AgencyPolicyRef" => $xml_data->Body->AgencyPolicyRef,
							"PolicyStatus" => $xml_data->Body->PolicyStatus,
							"TotalPremium" => $xml_data->Body->TotalPremium,
						]);
				}else{
					$message = !empty($message) ? $message : $xml_data->Head->ErrorMessage;
					$policy_arr = [
						"project_name" => $policy_info->project_name,
						"insured_amount" => $policy_info->insured_amount,
						"premium_total" => $policy_info->premium_total,
						"price_day" => $policy_info->price_day,
						"is_bill" => $policy_info->is_bill,
						'effect_date' => $policy_info->effect_date,
						"number" => $policy_info->number,
					];
					return $this->render ('detail',[
						"message" => $message,
						"id" => $policy_id,
						"policy" => $policy_arr
					]);
				}
			}
			// 立即支付
			return $this->redirect(['/pay/order','id'=>$policy_id]);
		}

		$policy_arr  = [];
		if ($policy_info) {
			// 确认成功
			$policy_arr = [
				"project_name" => $policy_info->project_name,
				"insured_amount" => $policy_info->insured_amount,
				"premium_total" => $policy_info->premium_total,
				"price_day" => $policy_info->price_day,
				"is_bill" => $policy_info->is_bill,
				'effect_date' => $policy_info->effect_date,
				"number" => $policy_info->number,
			];
		}
		
		return $this->render ('detail',[
			"message" => $message,
			"id" => $policy_id,
			"policy" => $policy_arr
		]);
	}

	/**
	 * @name 填写产品相关信息
	 */
	public function actionStep(){
		$request = $this->request;
		// 登录态
		$user_id = $this->user_id;
		
		// 当前所选计划 ID
		$price_id = trim($request->get('id',''));
		$source = trim($request->get('source',''));
		// plan_code 查询产品信息
		$this->_getInsurancePolicy($price_id,$user_id,'',$source);


		return $this->render ('step',[
			"price_id" => $price_id,
			"source" => $source,
		]);
	}

	/**
	 * 解决重定向302的问题
	 */
	public function actionPostData(){
		$request = $this->request;
		Yii::$app->response->format = Response::FORMAT_JSON;
		$price_id = trim($request->get('id',''));
		$source = trim($request->get('source',''));
		$user_id = $this->user_id;
		// plan_code 查询产品信息
		$policy_info = $this->_getInsurancePolicy($price_id,$user_id,trim($request->post('destination')),$source);
		$policy_id   = InsurancePolicy::insertRecord($policy_info);

		//请求邀请订单接口
		$state = InsurancePolicy::YES_PAY;
		$token = InsurancePolicy::TOKEN;
		$url = InsurancePolicy::INVITE_ORDER."?id=$user_id&policy_id=$policy_id&state=$state&token=$token";
		$invite = file_get_contents($url);

		// 检查数据有效性
		$username  = trim($request->post('username'));
		$error_message = [
			"code" => -1,
			"msg"  => "",
			"data" => ""
		];
		if (empty($username)) {
			$error_message["msg"] = "请输入正确的投保人姓名";
			return $error_message;
		}

		$id_card_no  = trim($request->post('id_card'));
		if (empty($id_card_no)) {
			$error_message["msg"] = "请输入正确的投保人身份证号码";
			return $error_message;
		}
		$id_card_res  = $this->_handleIdCardNumber($id_card_no);
		$id_card_type = trim($request->post('id_type'));
		
		if ($id_card_type == 1 && $id_card_res['error'] != 2) {
			$error_message["msg"] = "投保人身份证号码格式错误";
			return $error_message;
		}

		if (trim($request->post('person_re_type') != 1)) {
			$person_name  = trim($request->post('person_name'));
			if (empty($person_name)) {
				$error_message["msg"] = "请输入正确的被保险人姓名";
				return $error_message;
			}

			$id_card_no  = trim($request->post('person_card_no'));
			if (empty($id_card_no)) {
				$error_message["msg"] = "请输入正确的被保险人身份证号码";
				return $error_message;
			}

			$person_card_no = trim($request->post('person_card_no'));
			$person_card_type = trim($request->post('person_id_type'));
			$person_bir_day = trim($request->post('person_birthday'));
			if ($person_card_no && $person_card_type == 1) {
				$_card_res = $this->_handleIdCardNumber($person_card_no);
				if ($person_card_type && $_card_res['error'] != 2) {
					$error_message["msg"] = "被保险人身份证号码格式错误";
					return $error_message;
				}
			}else{
				if (empty($person_bir_day)) {
					$error_message["msg"] = "请选择被保险人的生日";
					return $error_message;
				}
			}
		}

		// 投保人信息
		$user_info  = [
			"policy_id" => $policy_id,
			"policy_holder_type" => 'I',
			"policy_holder_name" => trim($request->post('username')),
			"id_type"   => trim($request->post('id_type')),
			"id_number" => trim($request->post('id_card')),
			"birthday"  => date('Y-m-d H:i:s',strtotime(trim($request->post('birthday')))),
			"telephone" => trim($request->post('userphone')),
			"email"  => trim($request->post('useremail')),
			"gender" => trim(($request->post('sex'))),
		];
		$input_user_id = InsurancePolicyHolder::initRecord($user_info);
		if ($input_user_id) {
			// 更新数据
			$temp_insured_type = 1;
			// 投保人的关系
			if (trim($request->post('person_re_type') == 1)) {
				$temp_age = \app\services\ToolServices::birthday(trim(($request->post('birthday'))));
				if ($temp_age && $temp_age < 18) {
					$temp_insured_type = 2;
				}
				$person_type = trim($request->post('id_type'));
				$person_info = [
					"policy_id"    => $policy_id,
					"insured_id"   => $input_user_id,
					"insured_name" => trim($request->post('username')),
					"id_type"      => $person_type,
					"id_number"    => trim($request->post('id_card')),
					"birth_date"   => date('Y-m-d H:i:s',strtotime(trim(($request->post('birthday'))))),
					"mobile" 	=> trim($request->post('userphone')),
					"email" 	=> trim($request->post('useremail')),
					"insured_type" => $temp_insured_type,
				];
				if ($person_type == 1) {
					$result = $this->_handleIdCardNumber(trim($request->post('id_card')));
					if ($result['error'] == 2) {
						$person_info["birth_date"] = date('Y-m-d H:i:s',strtotime($result['birthday']));
					}
				}
				InsurancePolicyInsured::initRecord($person_info);
			}else{
				if ($request->post('person_name') || $request->post('person_card_no')) {
					$person_info = [
						"policy_id"    => $policy_id,
						"insured_id"   => $input_user_id,
						"insured_name" => trim($request->post('person_name')),
						"id_type"      => trim($request->post('person_id_type')),
						"id_number"    => trim($request->post('person_card_no')),
						"mobile" 	=> trim($request->post('person_phone')),
						"email" 	=> trim($request->post('person_email')),
						"insured_type" => $temp_insured_type,
					];
					if (trim($request->post('person_id_type')) == 1) {
						$result = $this->_handleIdCardNumber(trim($request->post('person_card_no')));
						if ($result['error'] == 2) {
							$person_info["birth_date"] = date('Y-m-d H:i:s',strtotime($result['birthday']));
							$temp_age = \app\services\ToolServices::birthday($result['birthday']);
							if ($temp_age && $temp_age < 18) {
								$person_info["insured_type"] = 2;
							}
						}
					}else{
						$person_bir_day = trim($request->post('person_birthday'));
						$person_info["birth_date"] = date('Y-m-d H:i:s',strtotime($person_bir_day));
						$temp_age = \app\services\ToolServices::birthday($person_bir_day);
						if ($temp_age && $temp_age < 18) {
							$person_info["insured_type"] = 2;
						}
					}
					InsurancePolicyInsured::initRecord($person_info);
				}
			}
			
			return [
				"code" => 0,
				"msg"  => "success",
				"data" => Url::toRoute('/buy/confirm?id='.$policy_id,true)
			];
		}

		return [
			"code" => -1,
			"msg"  => "请重新填写",
			// "data" => Url::toRoute('/buy/step?id='.$price_id,true)
		];
	}

	/**
	 * 获取订单操作
			// "destination" => trim(($request->post('destination'))),
	 */
	private function _getInsurancePolicy($id,$user_id,$destination='',$source=''){
		// plan_code 查询产品信息
		$insurance = InsurancePrice::getInsuranceById($id);
		if (empty($insurance)) {
			return [];
		}

		// 插入保单信息
		return [
			"account_type"=> 'wechat',
			"account_id"  => $user_id,
			"provider_id" => $insurance["provider_id"],
			'plan_code'   => $insurance["plan_code"],
			'project_name' => $insurance["project_name"],
			'insured_amount'  => $insurance["price_amount"],
			'premium_total'   => $insurance["price_amount"],
			'price_day' => $insurance["price_day"],
			'destination' => $destination,
			'soucre_tag'  => $source,
		];
	}

	/**
	 * @use 新增被保险人的
	 */
	public function actionAddInsurance(){
		// 处理接受的参数
		Yii::$app->response->format = Response::FORMAT_JSON;

		$user_id = $this->user_id;
		$price_id = trim($this->request->get('id',''));

		$insurance = InsurancePrice::getInsuranceById($price_id);
		if (empty($insurance)) {
			$this->redirect(['/index/list']);
		}

		$policy_info = $this->_getInsurancePolicy($price_id,$user_id);
		if (empty($policy_info)) {
			$this->redirect(['/index/list']);
		}

		$policy_id  = InsurancePolicy::initRecord($policy_info);

		$request = $this->request;

		if ($this->request->isPost) {
			// 投保人信息
			$user_info = [
				"policy_id" => $policy_id,
				"policy_holder_type" => 'I',
				"policy_holder_name" => trim($request->post('username')),
				"id_type"  => trim($request->post('id_type')),
				"id_number"  => trim($request->post('id_card')),
				"birthday" => date('Y-m-d',strtotime(trim($request->post('birthday')))),
				"telephone" => trim($request->post('userphone')),
				"email"  => trim($request->post('useremail')),
				"gender" => trim(($request->post('sex')))
			];
			$input_user_id = InsurancePolicyHolder::initRecord($user_info);

			$person_info = [
				"policy_id"    => $policy_id,
				"insured_id"   => $input_user_id,
				"insured_name" => trim($this->request->post('policy_name')),
				"id_type"    => trim($this->request->post('id_type')),
				"id_number"  => trim($this->request->post('id_number')),
				"mobile"  => trim($this->request->post('telephone')),
				"email" 	 => trim($this->request->post('email')),
			];

			if (InsurancePolicyInsured::initRecord($person_info)) {
				return [
					"code" => 0,
					'msg'  => 'success',
					'data' => $policy_id,
				];
			}else{
				return [
					"code" => -1,
					'msg'  => 'error',
				];
			}
		}
		return [
			"code" => -1,
			'msg'  => 'error',
		];
	}

	/**
	 * 处理身份证号码提取生日
	 */
	private function _handleIdCardNumber($IDCard,$format=1){
		$result['error']=0;//0：未知错误，1：身份证格式错误，2：无错误 
		$result['flag']='';//0标示成年，1标示未成年 
		$result['tdate']='';//生日，格式如：2012-11-15 
		if(!preg_match("/^(\d{15}$|^\d{18}$|^\d{17}(\d|X|x))$/",$IDCard)){ 
			$result['error']=1; 
			return $result; 
		}else{ 
		 	if(strlen($IDCard)==18){
				$tyear = intval(substr($IDCard,6,4)); 
				$tmonth= intval(substr($IDCard,10,2)); 
				$tday  = intval(substr($IDCard,12,2)); 
		 	}elseif(strlen($IDCard)==15){
				$tyear = intval("19".substr($IDCard,6,2)); 
				$tmonth= intval(substr($IDCard,8,2)); 
				$tday  = intval(substr($IDCard,10,2)); 
			}
			
			if($tyear>date("Y")||$tyear<(date("Y")-100)){
				$flag = 0; 
		  	}elseif($tmonth<0||$tmonth>12){
		  		$flag = 0; 
			}elseif($tday<0||$tday>31){
				$flag = 0; 
		  	}else{
		  		if($format){
		  			$tdate=$tyear."-".$tmonth."-".$tday;
		  		}else{
		  			$tdate=$tmonth."-".$tday; 
		  		}
		  		if((time()-mktime(0,0,0,$tmonth,$tday,$tyear))>18*365*24*60*60){ 
		  			$flag=0; 
		  		}else{
		  			$flag=1; 
		  		}
		  	} 
		}
		$result['error']   = 2;//0：未知错误，1：身份证格式错误，2：无错误 
		$result['isAdult'] = $flag;//0标示成年，1标示未成年 
		$result['birthday']= $tdate;//生日日期 
		return $result;
	}
}